//
//  ItemViewController.m
//  礼物go
//
//  Created by dllo on 16/5/24.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ItemViewController.h"
#import "ItemCategoryModel.h"
#import "ItemSubCategoryModel.h"
#import "ItemCateTableViewCell.h"
#import "itemSubCateCollectionViewCell.h"
#import "ItemTopCollReusableView.h"
#import "SubItemsViewController.h"
#import "ChooseItemViewController.h"

#define chooseBtnHeight 35
#define itemTableViewW 85
#define leftSpace 15
#define upSpace 35
#define collectionItemH 100
#define lineWidth 120


static NSString *const itemTableCell = @"itemTable";
static NSString *const collectionItemsCell = @"itemsCollectionCell";

@interface ItemViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDataSource,UICollectionViewDelegate>

@property(nonatomic,strong)UITableView *itemTableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UICollectionView *itemCollectionView;
@property(nonatomic,strong)NSMutableArray *collectionArray;
@property(nonatomic,strong)NSIndexPath *lastIndex;//记录最新被选中cell的下标
@property(nonatomic,assign)BOOL isSelectedTableViewCell;


@property(nonatomic,strong)UIButton *chooseGiftButton;

@end

@implementation ItemViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.translucent = NO;
    self.dataArray = [NSMutableArray array];
    
    //获取数据
    [self getItemData];
    
    //创建选礼按钮
    [self createChooseButton];
    
    //创建tableView
    [self createTableView];
    
    //创建collectionView
    [self createCollectionView];
    
    //默认保存第一个Tableviewcell的下标
    self.lastIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    //默认滑动到第一个cell
    
    //[self.itemTableView selectRowAtIndexPath:self.lastIndex animated:YES scrollPosition:UITableViewScrollPositionTop];
   //[self.itemTableView scrollToRowAtIndexPath:self.lastIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
   
    
    
    
    // Do any additional setup after loading the view.
}


-(void)getItemData{
    NSString *urlStr = @"http://api.liwushuo.com/v2/item_categories/tree";
    [LYNetworking ly_GetWithURL:urlStr Parameter:nil success:^(id result) {
        NSDictionary *dataDic = [result objectForKey:@"data"];
        NSArray *categories = [dataDic objectForKey:@"categories"];
        for (NSDictionary *dic in categories) {
            ItemCategoryModel *itemModel = [[ItemCategoryModel alloc] init];
            [itemModel setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:itemModel];
        }
        //默认第一个被选择
        ItemCategoryModel *itemCateModel = [self.dataArray firstObject];
        itemCateModel.isSelected = YES;
        
        [self.itemTableView reloadData];
        [self.itemCollectionView reloadData];
    } error:^(NSError *error) {
        
        
    }];
    
    
    
}

-(void)createChooseButton{
    self.chooseGiftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.chooseGiftButton.frame = CGRectMake(0, 0, SCREENWIDTH, chooseBtnHeight);
    [self.chooseGiftButton setImage:[UIImage imageNamed:@"chooseGifts"] forState:UIControlStateNormal];
    
    [self.view addSubview:self.chooseGiftButton];
    [self.chooseGiftButton addTarget:self action:@selector(chooseGiftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)createTableView{
    CGFloat y = CGRectGetMaxY(self.chooseGiftButton.frame);
    self.itemTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, y, itemTableViewW, self.view.frame.size.height - y - 64 - 49) style:UITableViewStylePlain];
    self.itemTableView.dataSource = self;
    self.itemTableView.delegate = self;
    [self.view addSubview:self.itemTableView];
    [self.itemTableView registerClass:[ItemCateTableViewCell class] forCellReuseIdentifier:itemTableCell];
    self.itemTableView.showsVerticalScrollIndicator = NO;


}

-(void)chooseGiftButtonAction:(UIButton *)button{
    ChooseItemViewController *chooseVC = [[ChooseItemViewController alloc] init];
    [self.navigationController pushViewController:chooseVC animated:YES];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ItemCateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:itemTableCell];
    ItemCategoryModel *itemCateModel = [self.dataArray objectAtIndex:indexPath.row];
    cell.itemModel = itemCateModel;
    //通过indexPath 确定model  通过model属性判断谁被选择
    if (itemCateModel.isSelected == YES) {
        cell.nameLabel.textColor = [UIColor redColor];
        cell.lineView.backgroundColor = [UIColor redColor];
        cell.backgroundColor = [UIColor whiteColor];
    }else{
        cell.nameLabel.textColor = [UIColor blackColor];
        cell.lineView.backgroundColor = [UIColor whiteColor];
        cell.backgroundColor = [UIColor colorWithRed:240 / 255.0 green:240 / 255.0 blue:240 / 255.0 alpha:1.0];
    }
    
    
    cell.selectionStyle =  UITableViewCellSelectionStyleNone;
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

//点击Tableviewcell让collectionview滚动
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    // 标记为当前选中的cell
    self.isSelectedTableViewCell = YES;
    //取出上次被选中的model
    ItemCategoryModel *itemlastModel = [self.dataArray objectAtIndex:self.lastIndex.row];
    //更改选中状态
    itemlastModel.isSelected = NO;
    
    //取出选中的model
    ItemCategoryModel *itemCurrent = [self.dataArray objectAtIndex:indexPath.row];
    //更改选中状态
    itemCurrent.isSelected = YES;
    
    //更新选中位置
    [self.itemTableView reloadRowsAtIndexPaths:@[self.lastIndex,indexPath] withRowAnimation:UITableViewRowAnimationNone];
    //重新记录下标位置
    self.lastIndex = indexPath;

    //collectionView滚动到哪个区的哪个item
    [self.itemCollectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] animated:YES scrollPosition:UICollectionViewScrollPositionTop];
    
}

//判断tableView和collectionView谁在滚动
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView != self.itemTableView) {
        if (scrollView.isDragging == YES) {
            self.isSelectedTableViewCell = NO;
        }
        
    }
}

//创建collectionView
-(void)createCollectionView{
     CGFloat y = CGRectGetMaxY(self.chooseGiftButton.frame);
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(upSpace, leftSpace, upSpace, leftSpace);
    flowLayout.itemSize = CGSizeMake((SCREENWIDTH - self.itemTableView.frame.size.width - 4 * leftSpace) / 3, collectionItemH);
    flowLayout.minimumLineSpacing = 30;
    flowLayout.headerReferenceSize = CGSizeMake(SCREENWIDTH - self.itemTableView.frame.size.width, 30);
    
    self.itemCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(self.itemTableView.frame.size.width, y, SCREENWIDTH - self.itemTableView.frame.size.width, self.itemTableView.frame.size.height) collectionViewLayout:flowLayout];
    self.itemCollectionView.dataSource = self;
    self.itemCollectionView.delegate = self;
    self.itemCollectionView.showsVerticalScrollIndicator = NO;
    self.itemCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.itemCollectionView];
    [self.itemCollectionView registerClass:[itemSubCateCollectionViewCell class] forCellWithReuseIdentifier:collectionItemsCell];
    
    [self.itemCollectionView registerClass:[ItemTopCollReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collHeader"];
    

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    itemSubCateCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionItemsCell forIndexPath:indexPath];
    ItemCategoryModel *itemCateModel = [self.dataArray objectAtIndex:indexPath.section];
    ItemSubCategoryModel *itemSub = [itemCateModel.subcategories objectAtIndex:indexPath.row];
    cell.subCategoryModel = itemSub;
    return cell;
}

//将要展示Cell视图时调用该方法
//-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
//}

//结束展示cell视图时调用
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    //获取一组当前显示的cell们的indexPath的数组(无序)
    NSArray *indexArray = [self.itemCollectionView indexPathsForVisibleItems];
    //给数组进行排序
    NSArray *orderArray = [indexArray sortedArrayUsingSelector:@selector(compare:)];
    
    //如果是点击Tableviewcell则不往下执行
    if (self.isSelectedTableViewCell) {
        return;
    }
    //取出上次选中的model
    ItemCategoryModel *itemModel = [self.dataArray objectAtIndex:self.lastIndex.row];
    itemModel.isSelected = NO;
    
    NSIndexPath *firstIndexPath = [orderArray firstObject];
    //得到当前下标位置
    NSIndexPath *currentIndexPath = [NSIndexPath indexPathForRow:firstIndexPath.section inSection:0];
    
    // 将当前下标对应的Tableviewcell对应的model值更新
    ItemCategoryModel *currentModel = [self.dataArray objectAtIndex:currentIndexPath.row];
    currentModel.isSelected = YES;
    
    
    
    [self.itemTableView reloadRowsAtIndexPaths:@[self.lastIndex,currentIndexPath] withRowAnimation:UITableViewRowAnimationNone];
    self.lastIndex = currentIndexPath;
    
    [self.itemTableView selectRowAtIndexPath:currentIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    
    

}



-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{        ItemTopCollReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"collHeader" forIndexPath:indexPath];
    headerView.backgroundColor = [UIColor whiteColor];
    
    ItemCategoryModel *itemModel = [self.dataArray objectAtIndex:indexPath.section];
    headerView.itemModel = itemModel;
    return headerView;
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
   ItemCategoryModel *itemCateModel = [self.dataArray objectAtIndex:section];
    
    return itemCateModel.subcategories.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArray.count;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ItemCategoryModel *itemCateModel = [self.dataArray objectAtIndex:indexPath.section];
    ItemSubCategoryModel *itemSubModel = [itemCateModel.subcategories objectAtIndex:indexPath.row];
    
    SubItemsViewController *subVC = [[SubItemsViewController alloc] init];
    subVC.naviTitle = itemSubModel.name;
    subVC.dataId = itemSubModel.myId;
    [self.navigationController pushViewController:subVC animated:YES];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
